from flask import request
from sqlalchemy import or_, and_  # 添加这行，导入需要的SQLAlchemy函数
from flaskapp.entity.Message import Message
from flaskapp.entity.User import User
from flaskapp.util.Redprint import Redprint
from flaskapp.util.Result import Result
from datetime import datetime
from sqlalchemy import or_, and_,desc,func
from flaskapp.util.Sqlalchemy import db
from flaskapp.entity.Message import MessageQuery

api = Redprint('chat')

@api.route('/messages', methods=['GET'])
def list_chat_history():
    """获取聊天历史记录列表"""
    current_user_id = request.args.get('user_id', type=int)
    if not current_user_id:
        return Result.error(400, '缺少用户ID')
    
    # 获取所有相关消息
    messages = Message.query.filter(
        or_(
            Message.sender_id == current_user_id,
            Message.receiver_id == current_user_id
        )
    ).order_by(Message.created_at.desc()).all()
        # 用字典存储每个对话者的最新消息
    chat_history = {}
    
    for msg in messages:
        # 确定对话者ID
        partner_id = msg.sender_id if msg.receiver_id == current_user_id else msg.receiver_id
        
        if partner_id not in chat_history:
            # 获取未读消息数
            unread_count = Message.query.filter_by(
                sender_id=partner_id,
                receiver_id=current_user_id,
                is_read=False
            ).count()
            
            chat_history[partner_id] = {
                'partner_id': partner_id,
                'last_message': msg.content,
                'last_time': msg.created_at.isoformat(),
                'unread_count': unread_count
            }
    # 转换为列表并按最后消息时间排序
    result = list(chat_history.values())
    result.sort(key=lambda x: x['last_time'], reverse=True)
    
    return Result.success(result, '获取聊天历史记录成功')

@api.route('/messages/send', methods=['POST'])
def send_message():
    """发送消息"""
    
    data = request.get_json()
    sender_id   = data.get('user_id')
    receiver_id = data.get('receiver_id')
    content     = data.get('content')
    house_id    = data.get('house_id')  # 如果有房源维度再存

    if not all([sender_id, receiver_id, content]):
        return Result.error(400, '缺少必要参数')

    # 验证用户存在
    sender   = User.query.filter_by(user_id=sender_id).first()
    receiver = User.query.filter_by(user_id=receiver_id).first()
    if not sender or not receiver:
        return Result.error(400, '发送者或接收者不存在')

    try:
        # 只传 __init__ 能接受的字段
        msg = Message(
            sender_id=sender_id,
            receiver_id=receiver_id,
            content=content
        )
        # 单独设置 sent_at
        msg.sent_at = datetime.utcnow()
        db.session.add(msg)
        db.session.commit()

        return Result.success(msg.to_dict(), '发送消息成功')
    except Exception as e:
        db.session.rollback()
        print(f"发送消息失败: {e}")
        return Result.error(500, f"发送消息失败: {str(e)}")

@api.route('/messages/history', methods=['GET'])
def get_chat_messages():
    """获取与特定用户的聊天记录"""
    current_user_id = request.args.get('user_id',   type=int)
    partner_id      = request.args.get('partner_id',type=int)
    page            = request.args.get('page',      1,      type=int)
    per_page        = request.args.get('per_page',  20,     type=int)

    if not current_user_id or not partner_id:
        return Result.error(400, '缺少必要参数')

    pagination = Message.query.filter(
        or_(
            and_(Message.sender_id   == current_user_id,
                 Message.receiver_id == partner_id),
            and_(Message.sender_id   == partner_id,
                 Message.receiver_id == current_user_id)
        )
    )\
    .order_by(Message.sent_at.desc())\
    .paginate(page=page, per_page=per_page)

    data = [{
        'id':         msg.message_id,
        'sender_id':  msg.sender_id,
        'content':    msg.content,
        'created_at': msg.sent_at.isoformat(),
        'is_read':    msg.is_read
    } for msg in pagination.items]
    # 标记对方发给我的未读消息为已读
    Message.query.filter_by(
        sender_id   = partner_id,
        receiver_id = current_user_id,
        is_read     = False
    ).update({'is_read': True})
    db.session.commit()
    
    return Result.success({
        'messages': data,
        'has_more': pagination.has_next
    }, '获取聊天记录成功')

@api.route('/messages/conversations', methods=['GET'])
def get_conversations():
    """获取当前用户的所有对话列表"""
    current_user_id = request.args.get('user_id', type=int)

    if not current_user_id:
        return Result.error(400, '缺少用户ID')

    # 查出用户所有相关的消息（作为发送方或接收方）
    messages = db.session.query(Message).filter(
        or_(
            Message.sender_id == current_user_id,
            Message.receiver_id == current_user_id
        )
    ).order_by(desc(Message.sent_at)).all()

    seen = set()
    result = []

    for msg in messages:
        # 确定对话的对方
        partner_id = msg.receiver_id if msg.sender_id == current_user_id else msg.sender_id

        key = (partner_id,)
        if key in seen:
            continue
        seen.add(key)

        partner = db.session.query(User).filter_by(user_id=partner_id).first()
        partner_name = partner.account_name if partner else '未知用户'

        # 统计未读消息数量（对方发来的未读）
        unread_count = db.session.query(func.count()).filter(
            Message.sender_id == partner_id,
            Message.receiver_id == current_user_id,
            Message.is_read == False
        ).scalar()

        result.append({
            'partner_id': partner_id,
            'partner_name': partner_name,
            'last_message': msg.content,
            'last_time': msg.sent_at.isoformat() if msg.sent_at else None,
            'unread_count': unread_count or 0
        })

    return Result.success(result, '获取会话列表成功')